package cn.nawang.ebeim.persist.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * User: 甘竞存
 * Date: 14-11-10
 * Time: 上午9:38
 * c3p0连接池
 */
public class DBPool {

    private static DBPool dbPool = null;

    private ComboPooledDataSource dataSource;

//    private  String driver="com.mysql.jdbc.Driver" ;
//    private String driver="net.sourceforge.jtds.jdbc.Driver" ;
    private String driver="org.sqlite.JDBC" ;

    private DBPool(){
        dataSource=new ComboPooledDataSource();
        try {
            dataSource.setDriverClass(driver);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        dataSource.setInitialPoolSize(10);
        dataSource.setMinPoolSize(1);
        dataSource.setMaxPoolSize(100);
        dataSource.setMaxStatements(50);
        dataSource.setMaxStatementsPerConnection(100);
        dataSource.setMaxIdleTime(6000);
    }

    public static DBPool getInstance(){
        if (dbPool==null){
            synchronized (DBPool.class){
                if (dbPool==null){
                    dbPool = new DBPool();
                }
            }
        }
        return dbPool;
    }

    public Connection getConnection(String url,String username,String password)   {
        try {
            if (dataSource.getJdbcUrl()==null||dataSource.getUser()==null||dataSource.getPassword()==null){
                dataSource.setJdbcUrl(url);
                dataSource.setUser(username);
                dataSource.setPassword(password);
            }
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException( "无法从数据源获取连接 ",e);
        }
    }

    @Override
    protected void finalize() throws Throwable {
        DataSources.destroy(dataSource);
        super.finalize();
    }
}
